ActiveAdmin.register Duel do

  form do |f|
    f.inputs "label" do
      f.input :a_id, as: :select, collection: Team.all
      f.input :b_id, as: :select, collection: Team.all
      if !f.object.a.nil?
        if f.object.b.id == 0
          f.input :winner_id, as: :select, collection: { f.object.a.name => f.object.a.id, "Dummy" => f.object.b.id }, required: false
        else
          f.input :winner_id, as: :select, collection: { f.object.a.name => f.object.a.id, f.object.b.name => f.object.b.id }, required: false
        end
      end
    end
    f.actions
  end

  controller do
    def permitted_params
      params.permit(duel: [:a_id, :b_id, :winner_id])
    end
    
    def update
      @duel = Duel.find(params[:id])
      @duel.update_attributes(permitted_params[:duel])
      redirect_to admin_duel_path(@duel)
    end
  end

  member_action :a_win, method: :put do
      @duel = Duel.find(params[:id])
      @duel.a_win
      redirect_to admin_event_path(@duel.event)
  end

  member_action :b_win, method: :put do
      @duel = Duel.find(params[:id])
      @duel.b_win
      redirect_to admin_event_path(@duel.event)
  end
end
